<template>
  <div>
    <div class="gva-search-box">
      <el-form ref="elSearchFormRef" :inline="true" :model="searchInfo" class="demo-form-inline" :rules="searchRule" @keyup.enter="onSubmit">
      <el-form-item label="创建日期" prop="createdAt">
      <template #label>
        <span>
          创建日期
          <el-tooltip content="搜索范围是开始日期（包含）至结束日期（不包含）">
            <el-icon><QuestionFilled /></el-icon>
          </el-tooltip>
        </span>
      </template>
      <el-date-picker v-model="searchInfo.startCreatedAt" type="datetime" placeholder="开始日期" :disabled-date="time=> searchInfo.endCreatedAt ? time.getTime() > searchInfo.endCreatedAt.getTime() : false"></el-date-picker>
       —
      <el-date-picker v-model="searchInfo.endCreatedAt" type="datetime" placeholder="结束日期" :disabled-date="time=> searchInfo.startCreatedAt ? time.getTime() < searchInfo.startCreatedAt.getTime() : false"></el-date-picker>
      </el-form-item>
        <el-form-item label="话题" prop="tid">
          <el-select v-model="searchInfo.tid" >
            <el-option
                v-for="item in topicOptions"
                :key="item.ID"
                :label="item.name"
                :value="item.ID"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="文本" prop="text">
          <el-input v-model="searchInfo.text" placeholder="相关内容" />
        </el-form-item>
        <el-form-item label="发布人" prop="name">
          <el-input v-model="searchInfo.name" placeholder="相关用户" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="search" @click="onSubmit">查询</el-button>
          <el-button icon="refresh" @click="onReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="gva-table-box">
        <el-table
        style="width: 100%"
        tooltip-effect="dark"
        :data="tableData"
        row-key="c_id"
        >
        <el-table-column align="center" label="日期" width="180">
            <template #default="scope">{{ formatDate(scope.row.create_at) }}</template>
        </el-table-column>
          <el-table-column align="center" label="话题" prop="topic" width="120" >
        </el-table-column>
        <el-table-column align="center" label="发布人" prop="name" width="120" />
        <el-table-column align="center" label="文本" prop="text" width="320" />
        <el-table-column label="图片" width="200" align="center">
            <template #default="scope">
              <el-image style="width: 100px; height: 100px" :src="getUrl(scope.row.img)" fit="img" v-if="scope.row.img!=''"/>
               <span v-else>无图健康圈</span>
            </template>
        </el-table-column>
        <el-table-column align="center" label="状态" prop="status" width="120">
            <template #default="scope">{{ formatBoolean(scope.row.status) }}</template>
        </el-table-column>
        <el-table-column align="center" label="浏览量" prop="views" width="120" />
        <el-table-column align="center" label="点赞量" prop="praise_num" width="120" />
        <el-table-column align="center" label="收藏量" prop="comment_num" width="120" />
        <el-table-column align="center" label="操作" min-width="120" fixed="right">
            <template #default="scope">
            <el-button type="primary" link class="table-button" @click="getComments(scope.row)">
                <el-icon style="margin-right: 5px"><InfoFilled /></el-icon>
                查看评论
            </el-button>
            <el-button type="primary" link icon="delete" @click="deleteRow(scope.row)">删除</el-button>
            </template>
        </el-table-column>
        </el-table>
        <div class="gva-pagination">
            <el-pagination
            layout="total, sizes, prev, pager, next, jumper"
            :current-page="page"
            :page-size="pageSize"
            :page-sizes="[10, 30, 50, 100]"
            :total="total"
            @current-change="handleCurrentChange"
            @size-change="handleSizeChange"
            />
        </div>
    </div>

    <el-dialog v-model="commentListFlag" title="查看评论" style="width:80%">
    <div class="gva-search-box">
      <el-form ref="elSearchFormRef" :inline="true" :model="cSearchInfo" class="demo-form-inline" :rules="cSearchRule" @keyup.enter="cOnSubmit">
      <el-form-item label="创建日期" prop="createdAt">
      <template #label>
        <span>
          创建日期
          <el-tooltip content="搜索范围是开始日期（包含）至结束日期（不包含）">
            <el-icon><QuestionFilled /></el-icon>
          </el-tooltip>
        </span>
      </template>
      <el-date-picker v-model="cSearchInfo.startCreatedAt" type="datetime" placeholder="开始日期" :disabled-date="time=> cSearchInfo.endCreatedAt ? time.getTime() > cSearchInfo.endCreatedAt.getTime() : false"></el-date-picker>
       —
      <el-date-picker v-model="cSearchInfo.endCreatedAt" type="datetime" placeholder="结束日期" :disabled-date="time=> cSearchInfo.startCreatedAt ? time.getTime() < cSearchInfo.startCreatedAt.getTime() : false"></el-date-picker>
      </el-form-item>
        <el-form-item label="文本" prop="text">
          <el-input v-model="cSearchInfo.text" placeholder="相关内容" />
        </el-form-item>
        <el-form-item label="发布人" prop="name">
          <el-input v-model="cSearchInfo.name" placeholder="相关用户" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="search" @click="cOnSubmit">查询</el-button>
          <el-button icon="refresh" @click="cOnReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
      <el-table :data="commentListData" tooltip-effect="dark" style="width: 100%">
        <el-table-column align="center" label="用户" prop="uid_name" width="200" />
        <el-table-column align="center" label="头像" width="120" >
          <template #default="scope">
            <CustomPic
              style="margin-top:12px"
              :pic-src="scope.row.avatar"
            />
          </template>
        </el-table-column>
        <el-table-column align="center" label="评论" prop="text" width="400" />
        <el-table-column align="center" label="回复他" width="180" prop="to_uid_name"/>
        <el-table-column align="center" label="评论时间" width="180">
          <template #default="scope">{{ formatDateYmd(scope.row.create_at) }}</template>
        </el-table-column>
          <el-table-column align="center" label="操作" min-width="120" fixed="right">
            <template #default="scope">
            <el-button type="primary" link icon="delete" @click="cDeleteRow(scope.row)">删除</el-button>
            </template>
        </el-table-column>
      </el-table>  
      <template #footer>
        <div class="gva-pagination">
            <el-pagination
            layout="commentsTotal, sizes, prev, pager, next, jumper"
            :current-page="cPage"
            :page-size="cPageSize"
            :page-sizes="[10, 30, 50, 100]"
            :total="commentsTotal"
            @current-change="cHandleCurrentChange"
            @size-change="cHandleSizeChange"
            />
        </div>
      </template>
    </el-dialog>

  </div>
</template>

<script>
export default {
  name: 'FdArticleAudio'
}
</script>

<script setup>
import {
  deleteCircle,
  deleteComment,
  getCommentsList,
  getHealthCircleList
} from '@/api/healthCircle'
import { getUrl } from '@/utils/image'
// 图片选择组件
import SelectImage from '@/components/selectImage/selectImage.vue'
import CustomPic from '@/components/customPic/index.vue'

// 全量引入格式化工具 请按需保留
import { getDictFunc, formatDate, formatDateYmd, formatBoolean, filterDict, ReturnArrImg, onDownloadFile } from '@/utils/format'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ref, reactive } from 'vue'


import {getTopicList} from "@/api/toPic";
import RichEdit from "@/components/richtext/rich-edit.vue";

const getLevelTwo = (one) =>{
  if (!one) return []
  return  levelTwoOptions.value.filter(item=>item.levelOneID === one)
}

const getLevelThree = (two) =>{
  if (!two) return []
  return  levelThreeOptions.value.filter(item=>item.levelTwoID === two)
}


const topicOptions = ref([])
const getTopicOptions = async () => {
  const topicList = await getTopicList({ page: 1, pageSize: 9999 })
  if (topicList.code === 0) {
    topicOptions.value = topicList.data.list
  }
}

getTopicOptions()

// 自动化生成的字典（可能为空）以及字段
const formData = ref({
        tid: undefined,
        text: '',
        img: "",
        status: 2,
        views: 0,
        praise_num: 0,
        comment_num: 0,
        })

// 验证规则
const rule = reactive({
})

const searchRule = reactive({
  createdAt: [
    { validator: (rule, value, callback) => {
      if (searchInfo.value.startCreatedAt && !searchInfo.value.endCreatedAt) {
        callback(new Error('请填写结束日期'))
      } else if (!searchInfo.value.startCreatedAt && searchInfo.value.endCreatedAt) {
        callback(new Error('请填写开始日期'))
      } else if (searchInfo.value.startCreatedAt && searchInfo.value.endCreatedAt && (searchInfo.value.startCreatedAt.getTime() === searchInfo.value.endCreatedAt.getTime() || searchInfo.value.startCreatedAt.getTime() > searchInfo.value.endCreatedAt.getTime())) {
        callback(new Error('开始日期应当早于结束日期'))
      } else {
        callback()
      }
    }, trigger: 'change' }
  ],
})
//弹窗条件查询
const cSearchRule = reactive({
  createdAt: [
    { validator: (rule, value, callback) => {
      if (cSearchInfo.value.startCreatedAt && !cSearchInfo.value.endCreatedAt) {
        callback(new Error('请填写结束日期'))
      } else if (!cSearchInfo.value.startCreatedAt && cSearchInfo.value.endCreatedAt) {
        callback(new Error('请填写开始日期'))
      } else if (cSearchInfo.value.startCreatedAt && cSearchInfo.value.endCreatedAt && (cSearchInfo.value.startCreatedAt.getTime() === cSearchInfo.value.endCreatedAt.getTime() || cSearchInfo.value.startCreatedAt.getTime() > cSearchInfo.value.endCreatedAt.getTime())) {
        callback(new Error('开始日期应当早于结束日期'))
      } else {
        callback()
      }
    }, trigger: 'change' }
  ],
})

const elFormRef = ref()
const elSearchFormRef = ref()

// =========== 表格控制部分 ===========
const page = ref(1)
const cPage = ref(1)
const total = ref(0)
const commentsTotal = ref(0)
const pageSize = ref(10)
const cPageSize = ref(10)
const tableData = ref([])
const commentListData = ref([])
const commentListFlag = ref(false)
const searchInfo = ref({})
const cSearchInfo = ref({})
// 重置
const onReset = () => {
  searchInfo.value = {}
  getTableData()
}

// 重置
const cOnReset = () => {
  cSearchInfo.value = {}
  getComments()
}

// 搜索
const onSubmit = () => {
  elSearchFormRef.value?.validate(async(valid) => {
    if (!valid) return
    page.value = 1
    pageSize.value = 10
    if (searchInfo.value.status === ""){
        searchInfo.value.status=2
    }
    getTableData()
  })
}

// 搜索
const cOnSubmit = () => {
  elSearchFormRef.value?.validate(async(valid) => {
    if (!valid) return
    page.value = 1
    cPageSize.value = 10
    if (cSearchInfo.value.status === ""){
        cSearchInfo.value.status=2
    }
    getComments(cSearchInfo.row)
  })
}

// 分页
const handleSizeChange = (val) => {
  pageSize.value = val
  getTableData()
}

// 分页
const cHandleSizeChange = (val) => {
  cPageSize.value = val
  getComments(cSearchInfo.row)
}


// 修改页面容量
const handleCurrentChange = (val) => {
  page.value = val
  getTableData()
}

// 修改页面容量
const cHandleCurrentChange = (val) => {
  cPage.value = val
  getComments(cSearchInfo.row)
}

// 查询
const getTableData = async() => {
  const table = await getHealthCircleList({ page: page.value, pageSize: pageSize.value, ...searchInfo.value })
  if (table.code === 0) {
    tableData.value = table.data.list
    total.value = table.data.total
    page.value = table.data.page
    pageSize.value = table.data.pageSize
  }
}

getTableData()

// ============== 表格控制部分结束 ===============

// 获取需要的字典 可能为空 按需保留
const setOptions = async () =>{
}

// 获取需要的字典 可能为空 按需保留
setOptions()

// 删除行
const deleteRow = (row) => {
    ElMessageBox.confirm('确定要删除吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
            deleteCircleFunc(row)
        })
    }

// 删除行
const cDeleteRow = (row) => {
  ElMessageBox.confirm('确定要删除吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
}).then(() => {
        deleteCommentFunc(row)
    })
}

// 行为控制标记（弹窗内部需要增还是改）
const type = ref('')

// 更新行
const updateFdArticleAudioFunc = async(row) => {
    const res = await findFdArticleAudio({ ID: row.c_id })
    type.value = 'update'
    if (res.code === 0) {
        formData.value = res.data.refdArticleAudio
        dialogFormVisible.value = true
    }
}


// 删除单行健康圈
const deleteCircleFunc = async (row) => {
  const res = await deleteCircle({ c_id: row.c_id })
  if (res.code === 0) {
      ElMessage({
              type: 'success',
              message: '删除成功'
          })
          if (tableData.value.length === 1 && page.value > 1) {
          page.value--
      }
      getTableData()
  }
}

// 删除单行评论
const deleteCommentFunc = async (row) => {
  const res = await deleteComment({ id: row.id })
  if (res.code === 0) {
      ElMessage({
              type: 'success',
              message: '删除成功'
          })
          if (commentListData.value.length === 1 && page.value > 1) {
          page.value--
      }
      getComments(cSearchInfo.row)
  }
}


// 弹窗控制标记
const dialogFormVisible = ref(false)


// 查看详情控制标记
const detailShow = ref(false)


// 打开详情弹窗
const openDetailShow = () => {
  detailShow.value = true
}


// 打开评论
const getComments = async (row) => {
  // 打开弹窗
    cSearchInfo.row=row
  const res = await getCommentsList({c_id:cSearchInfo.row.c_id, page: cPage.value, pageSize: cPageSize.value, ...cSearchInfo.value })
  if (res.code === 0) {
    
    commentListData.value = res.data.list
    commentListFlag.value = true
    commentsTotal.value = res.data.total
    cPage.value = res.data.page
    cPageSize.value = res.data.pageSize
  }
}


// 关闭详情弹窗
const closeDetailShow = () => {
  detailShow.value = false
  formData.value = {
          levelOneID: undefined,
          levelTwoID: undefined,
          levelThreeID: undefined,
          title: '',
          briefly: '',
          videoLink: '',
          text: '',

          details: '',
          status: true,
          isVip: false,
          praiseNum: 0,
          collectNum: 0,
          forwardNum: 0,
          }
}


// 打开弹窗
const openDialog = () => {
    type.value = 'create'
    dialogFormVisible.value = true
}

// 关闭弹窗
const closeDialog = () => {
    dialogFormVisible.value = false
    formData.value = {
        levelOneID: undefined,
        levelTwoID: undefined,
        levelThreeID: undefined,
        title: '',
        briefly: '',
        videoLink: '',
        text: '',
        details: '',
        status: true,
        isVip: false,
        praiseNum: 0,
        collectNum: 0,
        forwardNum: 0,
        }
}
// 弹窗确定
const enterDialog = async () => {
     elFormRef.value?.validate( async (valid) => {
             if (!valid) return
              let res
              switch (type.value) {
                case 'create':
                  res = await createFdArticleAudio(formData.value)
                  break
                case 'update':
                  res = await updateFdArticleAudio(formData.value)
                  break
                default:
                  res = await createFdArticleAudio(formData.value)
                  break
              }
              if (res.code === 0) {
                ElMessage({
                  type: 'success',
                  message: '创建/更改成功'
                })
                closeDialog()
                getTableData()
              }
      })
}

</script>

<style scope>

</style>
